"use strict"
const router =require('koa-router')();
const fs = require('fs');

function getrou(filePath){
    let tmp = filePath || __dirname;
    let files = fs.readdirSync(tmp)
    let routeFiles = files.filter(item =>{
        return item.endsWith('.js') && item !== 'index.js'
    })
    return routeFiles
}

function registry(router,routeFiles){
    routeFiles.forEach(item => {
        let tmpP  = __dirname +'/'+item;
        let obj = require(tmpP)
        for(let key in obj){
            let tmpA = key.split(' ');
            let rMe = tmpA[0];
            let rPath = tmpA[1];
            let rFunction =obj[key];
            if (rMe ==='get') {
                router.get(rPath,rFunction)
            }else if (rMe ==='put') {
                router.put(rPath,rFunction)
            }else if (rMe ==='post') {
                router.post(rPath,rFunction)
            }else if (rMe ==='delete') {
                router.delete(rPath,rFunction)
            }else{
                console.log("请求错误");
            }
        }
    });
    return router.routes();
}

module.exports =function () {
    let routeFiles = getrou();
    let reg =registry(router,routeFiles);
    return reg;
}